import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:hive/hive.dart';
import 'package:zywz/pages/profile/verification_code_dialog.dart';

import '../../bloc/profile/company_bloc.dart';
import '../../constants/ChinaCities.dart';
import '../../models/user.dart';

class TaxVerificationPage extends StatefulWidget {
  @override
  State<TaxVerificationPage> createState() => _TaxVerificationPageState();
}

class _TaxVerificationPageState extends State<TaxVerificationPage> {

  // 构建下拉选择框
  Widget _buildDropdown(String hintText, String? value, List<String> items, Function(String?) onChanged) {
    return Container(
      height: 50,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey.shade300),
        borderRadius: BorderRadius.circular(4),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: value,
          hint: Padding(
            padding: const EdgeInsets.only(left: 12),
            child: Text(
              hintText,
              style: TextStyle(color: Colors.grey.shade400, fontSize: 14),
            ),
          ),
          isExpanded: true,
          icon: const Icon(Icons.keyboard_arrow_down),
          padding: const EdgeInsets.symmetric(horizontal: 12),
          items: items.map((String item) {
            return DropdownMenuItem<String>(
              value: item,
              child: Text(item),
            );
          }).toList(),
          onChanged: onChanged,
        ),
      ),
    );
  }


  // 构建输入框
  Widget _buildTextField(String hintText, TextEditingController controller) {
    return Container(
      height: 50,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey.shade300),
        borderRadius: BorderRadius.circular(4),
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14),
          contentPadding: const EdgeInsets.symmetric(horizontal: 12),
          border: InputBorder.none,
        ),
      ),
    );
  }

  // 省份和城市
  String? _selectedProvince;
  String? _selectedCity;
  String? companyNameCurrn='';

  var mapData = {};


  // 表单控制器
  final TextEditingController _taxIdController = TextEditingController();
  final TextEditingController _taxRegisterNoController = TextEditingController();
  final TextEditingController _taxRegisterPwdController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();


  @override
  void initState(){
    super.initState();
    // _selectedProvince = ChinaCities.provinces[0];
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final company = Hive.box<User>('user_box').get('currentUser')?.appCompanyDto;
      companyNameCurrn = company?.name;
      // if(company != null){
      //   _taxIdController.text = company?.taxCode ?? '';
      //   _taxRegisterNoController.text = company?.taxPayerPhone ?? '';
      //   _taxRegisterPwdController.text = company?.nationalPwd ?? '';
      //   _phoneController.text = company?.taxPayerPhone ?? '';
      //   _selectedProvince = company?.province ?? '';
      //   _selectedCity = company?.city ?? '';
      //   setState(() {
      //     companyName = company?.name ?? '';
      //   });
      // }

      context.read<CompanyBloc>().add(LoadCompanyVeriEvent());



    });

  }


  // 使用示例
  void showVerificationDialog(BuildContext context) async {
    String? code = await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => VerificationCodeDialog(),
    );
    if (code != null) {
      print('用户输入的验证码: $code');
      context.read<CompanyBloc>().add(CompanyTaxVerifCodeEvent({'smsCode':code,'id':mapData['id'] ?? ''}));
    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF41C7DD),
        elevation: 0,
        centerTitle: true,
        title: const Text('税局信息验证',style: TextStyle(
          color: Colors.white,
          fontSize: 18.0,
          fontWeight: FontWeight.bold,
        ),),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Container(
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFFE3F2FD), Colors.white],
                stops: [0.0, 0.3],
              ),
              borderRadius: BorderRadius.circular(16),
            ),
            child: SingleChildScrollView(
              child: Center(
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(24.0),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.1),
                        blurRadius: 10,
                        offset: const Offset(0, 5),
                      ),
                    ],
                  ),
                  child: BlocConsumer(
                    bloc: context.read<CompanyBloc>(),
                    buildWhen: (previous, current) => current is CompanySuccess,
                    listener: (context, state) {
                      EasyLoading.dismiss(animation: false);
                      if(state is CompanyErrorState){
                        EasyLoading.showToast(state.message);
                      }
                      if(state is CompanyLoadState){
                        EasyLoading.show(status: '加载中...');
                      }else if(state is CompanyVerifyDialg){
                          if(state.code == 201){
                            EasyLoading.showToast('验证成功');
                            context.pop();
                          }else{
                            showVerificationDialog(context);
                          }
                      }
                    },
                    builder: (context, state) {

                      if(state is CompanySuccess){
                        _selectedProvince = state.data['province'] ?? "江苏省";
                        _selectedCity = state.data['city'] ?? "南京市";
                        mapData = state.data ?? {};

                          _taxIdController.text = state.data['taxCode'] ?? '';
                          _taxRegisterNoController.text = state.data['nationalName'] ?? '';
                          _taxRegisterPwdController.text = state.data['nationalPwd'] ?? '';
                          _phoneController.text = state.data['taxPayerPhone'] ?? '';

                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 公司名称
                            Padding(
                              padding: const EdgeInsets.only(bottom: 24),
                              child: Center(
                                child: Text(
                                  state.data['accountBookName']  ??  companyNameCurrn ?? '',
                                  style: const TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.black,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                            ),

                            // 地区
                            const Text(
                              '地区',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.black,
                              ),
                            ),
                            const SizedBox(height: 8),

                            // 省份和城市选择器
                            Row(
                              children: [
                                Expanded(
                                  child: _buildDropdown(
                                    '省份',
                                    _selectedProvince,
                                    ChinaCities.provinces,
                                        (value) {
                                      setState(() {
                                        _selectedProvince = value;
                                        _selectedCity = null; // 重置城市选择
                                      });
                                    },
                                  ),
                                ),
                                const SizedBox(width: 5),
                                const Text('-'),
                                const SizedBox(width: 5),
                                Expanded(
                                  child: _buildDropdown(
                                    '城市',
                                    _selectedCity,
                                    _selectedProvince != null ?  ChinaCities.cities[_selectedProvince]! : [],
                                        (value) {
                                      setState(() {
                                        _selectedCity = value;
                                      });
                                    },
                                  ),
                                ),
                              ],
                            ),

                            const SizedBox(height: 24),

                            // 社会信用统一代码/纳税人识别号
                            const Text(
                              '社会信用统一代码/纳税人识别号',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.black,
                              ),
                            ),
                            const SizedBox(height: 8),

                            _buildTextField('请输入社会信用统一代码/纳税人识别号', _taxIdController),

                            const SizedBox(height: 24),

                            // 电子税务局登录账号
                            const Text(
                              '电子税务局登录账号',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.black,
                              ),
                            ),
                            const SizedBox(height: 8),
                            _buildTextField('请输入电子税务局登录账号', _taxRegisterNoController),
                            const SizedBox(height: 24),

                            // 电子税务局登录密码
                            const Text(
                              '电子税务局登录密码',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.black,
                              ),
                            ),
                            const SizedBox(height: 8),
                            _buildTextField('电子税务局登录密码', _taxRegisterPwdController),
                            const SizedBox(height: 24),

                            // 对应手机号
                            const Text(
                              '对应手机号',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.black,
                              ),
                            ),
                            const SizedBox(height: 8),
                            _buildTextField('请输入对应手机号', _phoneController),
                            const SizedBox(height: 24),

                            // 进行验证按钮
                            GestureDetector(
                              onTap: (){
                                Map<String, dynamic> param = {
                                  'accountBookName': mapData['accountBookName'] ?? companyNameCurrn ?? '',
                                  'taxCode': _taxIdController.text,
                                  'nationalName': _taxRegisterNoController.text,
                                  'nationalPwd': _taxRegisterPwdController.text,
                                  'taxPayerPhone': _phoneController.text,
                                  'taxPayerPhone': _phoneController.text,
                                  'province': _selectedProvince,
                                  'city': _selectedCity,
                                  'loginWay': '2',
                                  'source': '3',
                                };

                                if(param['taxCode']!.isEmpty){
                                  EasyLoading.showToast('请输入社会信用统一代码/纳税人识别号');
                                  return;
                                }
                                if(param['nationalName']!.isEmpty){
                                  EasyLoading.showToast('请输入电子税务局登录账号');
                                  return;
                                }
                                if(param['nationalPwd']!.isEmpty){
                                  EasyLoading.showToast('请输入电子税务局登录密码');
                                  return;
                                }
                                if(param['taxPayerPhone']!.isEmpty){
                                  EasyLoading.showToast('请输入对应手机号');
                                  return;
                                }
                                context.read<CompanyBloc>().add(CompanyTaxVerificationEvent(param));
                              },
                              child: Align(
                                alignment: Alignment.center,
                                child: Container(
                                  width: 200,
                                  height: 36,
                                  decoration: BoxDecoration(
                                    color: const Color(0xFF4DD0E1),
                                    borderRadius: BorderRadius.circular(24),
                                  ),
                                  child: const Center(
                                    child: Text(
                                      '进行验证',
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        );
                      }
                      return SizedBox(
                        height: 300,
                        child: Center(
                          child: CircularProgressIndicator(),
                        ),
                      );
                    },
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
